package model

import (
	"fmt"
	common "gocode.com/m/common"
	"gorm.io/driver/mysql"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"strings"
)

var DB *gorm.DB

func chooseDB() (db *gorm.DB, error error) {
	switch strings.ToLower(common.DatabaseType) {
	case "mysql":
		fmt.Println("using mysql")
		dsn := "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
		db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
		if err != nil {
			panic("failed to connect database")
		}
		return db, nil
	case "sqlite":
		fmt.Println("using sqlite")
		db, error := gorm.Open(sqlite.Open(common.SQLitePath), &gorm.Config{})
		return db, error
	}
	return nil, nil
}

func migrateDatabase(db *gorm.DB) {
	fmt.Println("database migration started")
	//初始化表
	err := db.AutoMigrate(&Project{}, &SysUser{})
	if err != nil {
		panic("failed to migrate database")
	}
}

func InitDatabase() {
	db, error := chooseDB()
	// 将数据库连接给DB
	DB = db
	if error != nil {
		panic("failed to connect database")
	}
	sqlDB, err := db.DB()
	if err != nil {
		panic("failed to connect database")
	}
	fmt.Println(sqlDB)
	fmt.Println("connect db success")
	migrateDatabase(db)
}

func CloseDB() error {
	sqlDB, err := DB.DB()
	if err != nil {
		return err
	}
	err = sqlDB.Close()
	return err
}
